var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";
function result(status,data,msg){
    this.status = status;
    this.data = data || {};
    this.msg = msg;
}
const HASHMAP = {
    username:'用户名',
    msg:'消息'
};
function InsertMsg (req,res){
    MongoClient.connect(url,{useNewUrlParser:true},async function(err,db){
        if(err) throw err ;
        let dbo = db.db("mongo");
        let reqdata = {
            hash:Math.random().toString(36).substr(2,10),
            username:req.body.user,
            timestamp:Date.parse(new Date())/1000,
            msg:req.body.content
        };
        for(var i in reqdata){
            if(!reqdata[i]){
                res.send(new result(110,'',HASHMAP[i]+'未填写！'));
                return
            }
        };  
        let data = {
            ids:await dbo.collection('msgids').findOneAndUpdate({"type":"msg"},{$inc:{'idx':1}},{returnNewDocument :true}),
            username:reqdata.username,
            timestamp:reqdata.timestamp,
            msg:reqdata.msg
        }
        dbo.collections('chat').insertOne(data,function(er,ok){
            if(er) throw er;
            db.close();
        });
        res.send(new result(200,{},'ok'));
    })
}

module.exports = InsertMsg